﻿using System;
using System.Reflection;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using MethodWorx.CMS.TemplateLanguage;
using MethodWorx.CMS.Web;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MethodWorx.CMS.Content;
using MethodWorx.CMS.TemplateParser.Compiler;

namespace MethodWorx.CMS.TemplateParser.Tests
{
    [TestClass]
    public class TemplateCompilerTests
    {
        [TestMethod]
        public void TestSimpleCompilationOfSingleElement()
        {
            object result = CompileTemplate("<sometemplate />");

            Assert.AreEqual("<sometemplate />", result);
        }

        [TestMethod]
        public void TestSimpleCompilationOfSingleElementWithChild()
        {
            object result = CompileTemplate("<sometemplate><child /></sometemplate>");

            Assert.AreEqual("<sometemplate><child /></sometemplate>", result);
        }

        [TestMethod]
        public void TestSimpleCompilationOfSingleElementWithChildAndAttributes()
        {
            object result = CompileTemplate("<sometemplate><child attr1=\"abcdef\"/></sometemplate>");

            Assert.AreEqual("<sometemplate><child attr1=\"abcdef\" /></sometemplate>", result);
        }


        [TestMethod]
        public void TestSimpleCompilationOfSingleElementWithChildAndAttributesAndText()
        {
            object result = CompileTemplate("<sometemplate>Text Before<child attr1=\"abcdef\"/>Text After</sometemplate>");

            Assert.AreEqual("<sometemplate>Text Before<child attr1=\"abcdef\" />Text After</sometemplate>", result);
        }


        [TestMethod]
        public void TestSimpleCompilationOfSingleElementWithChildAndAttributesAndTextAndVariable()
        {
            object result = CompileTemplate("<sometemplate><var:set var=\"var1\" value=\"Variable Value\"/>Text Before<child attr1=\"abcdef\"/>{var1}</sometemplate>");

            Assert.AreEqual("<sometemplate>Text Before<child attr1=\"abcdef\" />Variable Value</sometemplate>", result);
        }



        private object CompileTemplate(string templateText)
        {
            DefaultParserFactory.Add(new SetVar());

            PageTemplate pt = new PageTemplate();
            pt.Template = templateText;

            ParsingEngine pe = new ParsingEngine(null, pt, null, null, "");

            var compiler = pe.GetCompiler();
            var compiled = compiler.Compile(new CmsRequestContext(), null);

            return compiled.GetType().InvokeMember("Execute",
                                                   BindingFlags.InvokeMethod | BindingFlags.Instance |
                                                   BindingFlags.Public, null, compiled, null);
        }
    }
}
